const db = require('../config/db');

const getChatHistory = (req, res) => {
  const { userId1, userId2 } = req.params;
  
  db.all(
    `SELECT * FROM messages 
     WHERE (sender_id = ? AND receiver_id = ?)
     OR (sender_id = ? AND receiver_id = ?)
     ORDER BY timestamp ASC`,
    [userId1, userId2, userId2, userId1],
    (err, messages) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      const formattedMessages = messages.map(msg => ({
        id: msg.id,
        senderId: msg.sender_id,
        receiverId: msg.receiver_id,
        content: msg.message,
        isRead: msg.is_read,
        timestamp: msg.timestamp
      }));
      res.json(formattedMessages);
    }
  );
};

module.exports = { getChatHistory }; 